package com.wxsong.authplatform.authweb.service.users;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wxsong.authplatform.authweb.dao.users.UserDao;
import com.wxsong.authplatform.authweb.exception.InstantException;
import com.wxsong.authplatform.authweb.model.role.Role;
import com.wxsong.authplatform.authweb.model.users.Users;
import com.wxsong.authplatform.authweb.util.ObjectUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService{

    @Resource
    private UserDao userDao;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public Users getByUserName(String userName) {
        return userDao.getByUserName(userName);
    }

    @Override
    public List<Users> list(int from, int pageSize, Map<String, Object> paramMap) {
        return userDao.list(from, pageSize, paramMap);
    }

    @Override
    public Long count(Map<String, Object> paramMap) {
        return userDao.count(paramMap);
    }

    @Override
    public int add(Users users) {
        users.encryPassword();
        return userDao.add(users);
    }

    @Override
    public int updateInfo(Long id, String name, int age, Timestamp birth){
        Map paramMap = Maps.newHashMap();
        paramMap.put("id", id);
        paramMap.put("name", name);
        paramMap.put("age", age);
        paramMap.put("birth", birth);
        return userDao.update(paramMap);
    }

    @Override
    public int delete(Long[] ids) {
        return userDao.delete(ids);
    }

    @Override
    public Users getById(Long id) {
        return userDao.getById(id);
    }

    @Override
    public List<Role> hasRoles(Long[] ids) {
        if(ids == null || ids.length < 1){
            return Lists.newArrayList();
        }
        return userDao.hasRoles(ids);
    }

    @Override
    public List<Role> noRoles(Long[] ids) {
        return userDao.noRoles(ids);
    }

    @Override
    public int modifyAuth(String ids, Long userId) {
        Users users = userDao.getById(userId);
//        users.modifyAuth(ids);
        Map paramMap = null;
        try {
            paramMap = ObjectUtil.toMap(users);
        } catch (Exception e) {
            throw new InstantException("修改权限数据时，对象转换为map出现异常", e);
        }
        return userDao.update(paramMap);
    }


}
